<script setup>
import { createTableDataApi, deleteTableDataApi, getTableDataApi, updateTableDataApi } from "@@/apis/tables"
import { getProductList, searchProduct, addProduct, deleteProduct, updateProduct, batchDeleteProduct } from "@@/apis/product"
import { usePagination } from "@@/composables/usePagination"
import { CirclePlus, Delete, Download, Refresh, RefreshRight, Search } from "@element-plus/icons-vue"
import { cloneDeep } from "lodash-es"
import { onMounted, ref, reactive, watch } from "vue"

defineOptions({
  // 命名当前组件
  name: "Consulting"
})

const loading = ref(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// #region 增
const DEFAULT_FORM_DATA = {
  id: undefined,
  name: "",
  password: "",
  description: "",
  image: "",
  isActive: true,
  price: undefined,
  stock: undefined
}
const dialogVisible = ref(false)
const formRef = ref(null)
const formData = ref(cloneDeep(DEFAULT_FORM_DATA))
const formRules = {
  name: [{ required: true, trigger: "blur", message: "请输入商品名称" }],
  image: [{ required: true, trigger: "blur", message: "请输入图片地址" }],
  description: [{ required: true, trigger: "blur", message: "请输入商品描述" }],
  price: [{ required: true, trigger: "blur", message: "请输入价格" }],
  stock: [{ required: true, trigger: "blur", message: "请输入库存" }]
}
function handleCreateOrUpdate() {
  formRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error("表单校验不通过")
      return
    }
    loading.value = true
    const api = formData.value.id === undefined ? addProduct : updateProduct
    api(formData.value).then(() => {
      ElMessage.success("操作成功")
      dialogVisible.value = false
      getTableData()
    }).finally(() => {
      loading.value = false
    })
  })
}
function resetForm() {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
// #endregion

// #region 删
function handleDelete(row) {
  ElMessageBox.confirm(`正在删除商品：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteProduct(row.id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}

// 批量删除功能
const tableRef = ref(null)

function handleBatchDelete() {
  const selection = tableRef.value?.getSelectionRows()
  if (!selection || selection.length === 0) {
    ElMessage.warning("请至少选择一条数据")
    return
  }
  
  ElMessageBox.confirm(`正在删除选中的 ${selection.length} 个商品，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    const ids = selection.map(item => item.id)
    batchDeleteProduct(ids).then(() => {
      ElMessage.success("批量删除成功")
      getTableData()
    })
  })
}
// #endregion

// #region 改
function handleUpdate(row) {
  dialogVisible.value = true
  formData.value = cloneDeep(row)
}
// #endregion

// #region 查
const tableData = ref([])
const allTableData = ref([]) // 存储所有数据
const searchFormRef = ref(null)
const searchData = reactive({
  name: "",
})

const getTableData = (formData = null) => {
  loading.value = true
  getProductList(formData).then(({ data }) => {
    console.log('获取到的商品数据:', data)
    allTableData.value = data
    paginationData.total = data.length
    updateDisplayData()
  }).catch(() => {
    allTableData.value = []
    tableData.value = []
    paginationData.total = 0
  }).finally(() => {
    loading.value = false
  })
}

// 根据分页参数更新显示的数据
function updateDisplayData() {
  const start = (paginationData.currentPage - 1) * paginationData.pageSize
  const end = start + paginationData.pageSize
  tableData.value = allTableData.value.slice(start, end)
  console.log(`分页显示: 第${paginationData.currentPage}页, 每页${paginationData.pageSize}条, 显示${start + 1}-${Math.min(end, allTableData.value.length)}条, 共${allTableData.value.length}条`)
}

function handleSearch() {
  loading.value = true
  searchProduct(searchData).then(({ data }) => {
    console.log('获取到的商品数据:', data)
    allTableData.value = data
    paginationData.total = data.length
    updateDisplayData()
  }).catch(() => {
    allTableData.value = []
    tableData.value = []
    paginationData.total = 0
  }).finally(() => {
    loading.value = false
  })
}
function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
}

// #endregion

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], () => {
  if (allTableData.value.length > 0) {
    updateDisplayData()
  }
})

// 初始化时获取数据
onMounted(() => {
  getTableData()
})
</script>

<template>
  <div class="app-container">
    <!-- <el-alert
      title="数据来源"
      type="success"
      description="由 Apifox 提供在线 Mock，数据不具备真实性，仅供简单的 CRUD 操作演示。"
      show-icon
    /> -->
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="商品名称">
          <el-input v-model="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="Refresh" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">
            新增
          </el-button>
          <el-button type="danger" :icon="Delete" @click="handleBatchDelete">
            批量删除
          </el-button>
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table ref="tableRef" :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="name" label="商品名称" align="center" />
          <el-table-column prop="description" label="商品描述" align="center" />
          <el-table-column prop="isActive" label="状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.isActive == '1'" type="primary" effect="plain" disable-transitions>
                上架
              </el-tag>
              <el-tag v-else type="warning" effect="plain" disable-transitions>
                下架
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" align="center" />
          <el-table-column prop="stock" label="库存" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">
                修改
              </el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :current-page="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id === undefined ? '新增用户' : '修改用户'"
      width="30%"
      @closed="resetForm"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="name" label="商品名称">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="image" label="图片地址">
          <el-input v-model="formData.image" placeholder="请输入图片地址" />
        </el-form-item>
        <el-form-item prop="description" label="商品描述">
          <el-input 
            v-model="formData.description" 
            placeholder="请输入商品描述" 
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </el-form-item>
        <el-form-item prop="isActive" label="状态">
          <el-select v-model="formData.isActive" placeholder="请选择状态">
            <el-option label="上架" :value="true" />
            <el-option label="下架" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item prop="price" label="价格">
          <el-input-number v-model="formData.price" placeholder="请输入价格" :min="0" :step="0.01" />
        </el-form-item>
        <el-form-item prop="stock" label="库存">
          <el-input-number v-model="formData.stock" placeholder="请输入库存" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="loading" @click="handleCreateOrUpdate">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.el-alert {
  margin-bottom: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>